package com.mayjean.common.spel;

import com.mayjean.common.util.SpringUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.expression.AnnotatedElementKey;
import org.springframework.expression.EvaluationContext;

import java.lang.reflect.Method;

/**
 * Abstract expression evaluator
 *
 * @author
 */
public class AbstractExpressionEvaluator {

	private final MapCacheExpressionEvaluator mapCacheExpressionEvaluator = new MapCacheExpressionEvaluator();

	/**
	 * eval SePL Param
	 *
	 * @param proceedingJoinPoint proceeding join point
	 * @param param               param
	 * @return value
	 */
	public String evalSePlParam(ProceedingJoinPoint proceedingJoinPoint, String param) {
		MethodSignature ms = (MethodSignature) proceedingJoinPoint.getSignature();
		Method method = ms.getMethod();
		Object[] args = proceedingJoinPoint.getArgs();
		Object target = proceedingJoinPoint.getTarget();
		Class<?> targetClass = target.getClass();
		EvaluationContext context = mapCacheExpressionEvaluator.createContext(method, args, target, targetClass, SpringUtil.getApplicationContext());
		AnnotatedElementKey elementKey = new AnnotatedElementKey(method, targetClass);
		return mapCacheExpressionEvaluator.evalAsText(param, elementKey, context);
	}
}
